package co.com.smart.persistence.entity;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import co.com.smart.persistence.entity.dto.SmartDepartamento;
import co.com.smart.persistence.entity.util.AbstractFacade;

/**
 * Session Bean implementation class DepartamentoFacade
 */
@Stateless(
		name		= "DepartamentoFacade", 
		mappedName 	= "ejb/DepartamentoFacade")
public class DepartamentoFacade extends AbstractFacade<SmartDepartamento> implements DepartamentoFacadeLocal {

	@PersistenceContext(unitName = "SmartServicesPU")
	
	private EntityManager em;
	
    /**
     * Default constructor. 
     */
    public DepartamentoFacade() {
    	super(SmartDepartamento.class);
    }
    
    @Override
    protected EntityManager getEntityManager() {
    	return em;
    }
    
    @Override
    public List<SmartDepartamento> filtrarDepatamento(SmartDepartamento entity) {
    	StringBuilder  sQuery = new StringBuilder("select d from SmartDepartamento d join d.smartPais p ");
		sQuery.append(" where p.smFhretiro is null ");
		
		if (entity.getSmartPais()  != null && entity.getSmartPais().getSmScpais() != null)
		{
			sQuery.append(" and p.smScpais = :scpais ");			
		}			

		if(entity.getSmCodepartamento() != null && !"".equals(entity.getSmCodepartamento().trim())){
			sQuery.append(" and d.smCodepartamento = :smCoPais ");
		}
		
		if(entity.getSmDsdepartamento() != null && !"".equals(entity.getSmDsdepartamento().trim())){
			sQuery.append(" and d.smCodepartamento like :smDsDepto ");
		}
		
		Query query = em.createQuery(sQuery.toString() );
		
		if (entity.getSmartPais()  != null && entity.getSmartPais().getSmScpais() != null)
		{
			query.setParameter("scpais", entity.getSmartPais().getSmScpais());	
		}
		
		if(entity.getSmCodepartamento() != null && !"".equals(entity.getSmCodepartamento().trim())){
			query.setParameter("smCoPais", entity.getSmCodepartamento());
		}
		
		if(entity.getSmDsdepartamento() != null && !"".equals(entity.getSmDsdepartamento().trim())){
			query.setParameter("smDsDepto", entity.getSmDsdepartamento());
		}
		
		return query.getResultList();		
    }
}
